package com.feityz.handler.sh;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.variable.Variable;
import com.bstek.uflo.process.handler.AssignmentHandler;
import com.bstek.uflo.process.node.TaskNode;
import com.feityz.common.Result;
import com.feityz.system.entity.Dept;
import com.feityz.system.entity.User;
import com.feityz.system.service.IDeptService;
import com.feityz.system.service.IParameterService;
import com.feityz.system.service.IUserService;
import com.feityz.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门主管
 */
@Component("shDeptLeader")
@ConditionalOnProperty(name = "system", havingValue = "sh")
public class ShDeptLeaderHandler implements AssignmentHandler {
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IParameterService parameterService;

    @Override
    public Collection<String> handle(TaskNode taskNode, ProcessInstance processInstance, Context context) {

        String prometer = processInstance.getPromoter();

        User user = userService.getById(prometer);

        Assert.notNull(user,"找不到人员");

        Long deptId = user.getDept();

        Assert.notNull(deptId,"发起人部门为空");

        Dept dept = deptService.getById(deptId);

        Assert.notNull(dept,"系统中找不到发起人的部门");

        List<User> users = userService.lambdaQuery().eq(User::getDept,deptId).inSql(
                User::getId,"select user_id from re_user_role where role_id = (" +
                        "select id from sys_role where role_num='BMZG'" +
                        ")"
        ).list();

        Assert.notEmpty(users,"找不到发起人部门下的主管人员");

        List<String> result = users.stream().map(e->e.getId().toString()).collect(Collectors.toList());

        return result;
    }

    @Override
    public String desc() {
        return "发起人员部门主管";
    }
}
